package com.example.android

import android.app.Application
import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log

/**
 * @ClassName MyApplication
 * @Author Ryan Kamanri
 * @Date 2022/6/1
 * @Description 全局Application对象封装
 **/
class MyApplication : Application() {

    private lateinit var _ServicesObject: ServicesObject
    private var _IsServicesConnected = false

    val ServicesObject
        get() = _ServicesObject

    private var _OnServicesConnected: () -> Unit = { }
    fun SetOnServicesConnected(onServicesConnected: () -> Unit) {
        _OnServicesConnected = onServicesConnected
        if(_IsServicesConnected)
            _OnServicesConnected()
    }

    override fun onCreate() {
        super.onCreate()

        val intent = Intent(applicationContext, MyServices::class.java)

        bindService(intent, object: ServiceConnection{
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                _IsServicesConnected = true
                _ServicesObject = (service as ServicesObject)
                _OnServicesConnected()
                Log.d(toString(), "Service $_ServicesObject Has Connected")
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                _IsServicesConnected = false
                Log.w(toString(), "Service $_ServicesObject Has Disconnected")
            }
        }, Service.BIND_AUTO_CREATE or Service.BIND_IMPORTANT)


    }
}

